package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class ITHomeRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;

    public Map<String, Object> handleRoute(boolean noCache) throws Exception {
        Map<String, Object> listResult = getList(noCache);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "ithome");
        routeData.put("favicon", "https://www.ithome.com/favicon.ico");
        routeData.put("title", "IT之家");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "热榜");
        routeData.put("link", "https://m.ithome.com/rankm/");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据到redis
        cacheDataInRedis.cacheData("ithome:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index+1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private String replaceLink(String url, boolean getId) {
        String pattern = "[html|live](/\\d+)\\.htm";
        String id = url.replaceAll(pattern, "$1");
        return getId
                ? id
                : "https://www.ithome.com/0/" + id.substring(0, 3) + "/" + id.substring(3) + ".htm";
    }

    private Map<String, Object> getList(boolean noCache) throws Exception {
        String url = "https://m.ithome.com/rankm/";
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.body();

        // 使用ObjectMapper解析HTML字符串
        JsonNode doc = objectMapper.readTree(body);
        JsonNode listDom = doc.at("/rank-box/placeholder");

        List<Map<String, Object>> listData = listDom.findValuesAsText("a").stream()
                .map(item -> {
                    String href = item;
                    Map<String, Object> itemData = new LinkedHashMap<>();
                    itemData.put("title", doc.at("/plc-title").asText().trim());
                    itemData.put("url", href != null ? replaceLink(href, false) : null);
                    itemData.put("mobileUrl", href != null ? href : null);
                    return itemData;
                })
                .limit(12) // 只提取前12条
                .collect(Collectors.toList());

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("fromCache", false);
        result.put("updateTime", System.currentTimeMillis());
        result.put("data", listData);

        return result;
    }

    public Map<String, Object> getRouteAndDataCombined(boolean noCache) throws Exception {
        return handleRoute(noCache);
    }

    public Map<String, Object> getITHomeRanking() throws Exception {
        return getRouteAndDataCombined(false);
    }
}
